/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.service.impl;

import com.koron.common.bean.StaffBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.emergency.domain.EmergencyInstitutions;
import com.koron.emergency.domain.EmergencyInstitutionsStaff;
import com.koron.emergency.mapper.EmergencyInstitutionsMapper;
import com.koron.emergency.mapper.EmergencyInstitutionsStaffMapper;
import com.koron.emergency.service.api.EmergencyInstitutionsService;
import com.koron.emergency.util.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class EmergencyInstitutionsServiceImpl implements EmergencyInstitutionsService {

    private final String ROOT_PCODE = "-1";
    private final static  Logger logger = LoggerFactory.getLogger(EmergencyInstitutionsServiceImpl.class);

    @Override
    public MessageBean<Integer> save(StaffBean user, EmergencyInstitutions bean) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = null;
        try {
            if (StringUtils.isEmpty(bean.getName())) {
                msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_EMPTY_NAME.getCode());
                msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_EMPTY_NAME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getCorpCode())) {
                msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_EMPTY_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_EMPTY_CORPCODE.getDescription());
                return msg;
            }
            factory = new SessionFactory();
            if (StringUtils.isEmpty(bean.getPid())) {
                Integer count = factory.getMapper(EmergencyInstitutionsMapper.class).countAll(bean.getCorpCode());
                if (0 > count) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_PARENT_IS_EXIST.getCode());
                    msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_PARENT_IS_EXIST.getDescription());
                    return msg;
                }
            } else {
                if (!StringUtils.equals(ROOT_PCODE,bean.getPid())){
                    EmergencyInstitutions parent = queryOne(bean.getPid()).getData();
                    if (parent == null) {
                        factory.close(false);
                        msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_PARENT_NOT_EXIST.getCode());
                        msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_PARENT_NOT_EXIST.getDescription());
                        return msg;
                    }
                }
            }
            StringBuilder description = new StringBuilder();
            if (StringUtils.isEmpty(bean.getId())) {
                //新增操作
                //父节点是否存在；
                if (StringUtils.isNotEmpty(bean.getPid())&&!StringUtils.equals(ROOT_PCODE,bean.getPid())) {
                    EmergencyInstitutions parent = queryOne(bean.getPid()).getData();
                    if (parent == null) {
                        factory.close(false);
                        msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_EMPTY_CORPCODE.getCode());
                        msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_EMPTY_CORPCODE.getDescription());
                        return msg;
                    } else {
                        //先新增
                        Integer check=factory.getMapper(EmergencyInstitutionsMapper.class).checkDouble(bean.getName(),bean.getPid(),bean.getCorpCode(),null);
                        if (check>0){
                            msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_DOUBLE_NAME.getCode());
                            msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_DOUBLE_NAME.getDescription());
                            return msg;
                        }
                        bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                        bean.setAddTime(bean.getUpdateTime());
                        bean.setAddUser(bean.getUpdateUser());
                        bean.setAddUserName(bean.getUpdateUserName());
                        factory.getMapper(EmergencyInstitutionsMapper.class).insert(bean);
                        Integer subnumber = parent.getSubnumber();
                        parent.setSubnumber(subnumber + 1);
                        factory.getMapper(EmergencyInstitutionsMapper.class).update(parent);
                    }
                } else {
                    //将该节点作为父节点,先加父节点
                    bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                    bean.setAddTime(bean.getUpdateTime());
                    bean.setAddUser(bean.getUpdateUser());
                    bean.setAddUserName(bean.getUpdateUserName());
                    bean.setPid(ROOT_PCODE);
                    bean.setName("应急委员会");
                    if (factory.getMapper(EmergencyInstitutionsMapper.class).insert(bean) > 0)
                        description.append(",该水司暂时没有应急机构,您刚才的新增行为视为新增根节点操作");
                }
            } else {
                //修改操作
                EmergencyInstitutions entity = queryOne(bean.getId()).getData();
                if (null == entity) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_NOT_EXIST.getDescription());
                    return msg;
                }
                Integer check=factory.getMapper(EmergencyInstitutionsMapper.class).checkDouble(bean.getName(),bean.getPid(),bean.getCorpCode(),bean.getId());
                if (check>0){
                    msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_DOUBLE_NAME.getCode());
                    msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_DOUBLE_NAME.getDescription());
                    return msg;
                }
                factory.getMapper(EmergencyInstitutionsMapper.class).update(bean);
            }
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("保存成功" + description.toString());
            msg.setData(1);
            return msg;
        } catch (Exception e) {
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }finally {
            if (null != factory){
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Integer> delete(String id) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = null;
        try {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            factory = new SessionFactory();
            EmergencyInstitutions entity = queryOne(id).getData();
            if (null == entity) {
                factory.close(false);
                msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_NOT_EXIST.getDescription());
                return msg;
            }
            if (entity.getSubnumber() > 0) {
                factory.close(false);
                msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_IS_EXIST_CHILD.getCode());
                msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_IS_EXIST_CHILD.getDescription());
                return msg;
            }
            //查询该部门下是否存在人员
            Integer staffCount = factory.getMapper(EmergencyInstitutionsStaffMapper.class).countByInstitutionsId(id, null);
            if (staffCount > 0) {
                factory.close(false);
                msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_IS_EXIST_STAFF.getCode());
                msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_IS_EXIST_STAFF.getDescription());
                return msg;
            }
            //执行删除操作
            Integer value = factory.getMapper(EmergencyInstitutionsMapper.class).delete(id);
            if (value > 0) {
                if (StringUtils.isNotEmpty(entity.getPid())) {
                    //去查询父节点，减少父节点的子节点数量
                    EmergencyInstitutions parent = queryOne(entity.getPid()).getData();
                    if (null != parent) {
                        parent.setSubnumber(parent.getSubnumber() - 1);
                        factory.getMapper(EmergencyInstitutionsMapper.class).update(parent);
                    }
                }
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("删除成功");
                return msg;
            } else {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                return msg;
            }
        } catch (Exception e) {
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }finally {
            if (null != factory){
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<EmergencyInstitutions> queryOne(String id) {
        MessageBean<EmergencyInstitutions> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.EMERGENCYINSTITUTIONS_NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.EMERGENCYINSTITUTIONS_NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            EmergencyInstitutions entity = factory.getMapper(EmergencyInstitutionsMapper.class).queryOne(id);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询应急机构详情成功");
            msg.setData(entity);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<EmergencyInstitutions> queryCorpAll(String corpCode) {
        MessageBean<EmergencyInstitutions> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<EmergencyInstitutions> list = factory.getMapper(EmergencyInstitutionsMapper.class).queryAll(corpCode);
            if (null != list && list.size() > 0) {
                EmergencyInstitutions root = list.stream().filter(node -> node.getPid().equals(ROOT_PCODE)).findAny().get();
                if (null != root) {
                    construct(root, list);
                }
                msg.setData(root);
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("查询应急机构列表成功");
                return msg;
            } else {
                msg.setData(null);
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("查询应急机构列表成功");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<List<EmergencyInstitutions>> childList(String corpCode, String pid) {
        MessageBean<List<EmergencyInstitutions>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<EmergencyInstitutions> list = factory.getMapper(EmergencyInstitutionsMapper.class).queryByPid(corpCode, pid);
            msg.setData(list);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询该部门下子部门成功");
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    private void construct(EmergencyInstitutions root, List<EmergencyInstitutions> nodes) {
        try (SessionFactory factory = new SessionFactory()) {
            List<EmergencyInstitutionsStaff> staffList = factory.getMapper(EmergencyInstitutionsStaffMapper.class).queryByInstitutionsId(root.getId(), null, null, null);
            if (null != staffList && staffList.size() > 0) {
                List<String> names = staffList.stream().map(EmergencyInstitutionsStaff::getStaffName).collect(Collectors.toList());
                root.setStaffName(names);
            }
            List<EmergencyInstitutions> collect = nodes.stream().filter(node -> node.getPid().equals(root.getId())).collect(Collectors.toList());
            if (null != collect && !collect.isEmpty()) {
                root.setChildList(collect);
                collect.forEach(grid -> construct(grid, nodes));
            }
        }
    }

}
